package io.renren.modules.base.controller;

import io.renren.common.utils.R;
import io.renren.modules.base.service.UploadFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Description Created by
 */

@RestController
@RequestMapping("/api/upload")
public class UploadFilesController {

    private static final Logger log = LoggerFactory.getLogger(UploadFilesController.class);


    @Autowired
    private UploadFileService uploadFileService;


    /**
     * 返回R的单张图片接口
     * @param request
     * @return
     */
    @PostMapping("/image")
    public R singleFileUpload(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        String fileUpload = uploadFileService.uploadFile(files.get(0), "image");
        log.info("上传图片结果为： " + fileUpload.toString());
        return R.reOk(fileUpload);
    }

    /**
     * 返回R的多张图片接口
     * @param request
     * @return
     */
    @PostMapping("/images")
    public R singleFileUploads(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        List<String> fileUpload = uploadFileService.uploadFiles(files, "image");
        log.info("上传图片结果为： " + fileUpload.toString());
        return R.reOk(fileUpload);
    }

    /**
     * 返回单张的图片url的接口，只有URL字符串
     * @param request
     * @return
     */
    @PostMapping("/imageUrl")
    public String singleFileUploadUrl(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        String fileUpload = uploadFileService.uploadFile(files.get(0), "image");
        log.info("上传图片结果为： " + fileUpload.toString());
        return fileUpload;
    }

    /**
     * 压缩图片上传接口
     *
     * @param request
     * @param widthRate
     * @param heightRate
     * @return
     */
    @PostMapping("/compressedUpload")
    public R compressedUpload(HttpServletRequest request, Double widthRate, Double heightRate) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        return uploadFileService.compressedUpload(files, widthRate, heightRate);
    }


}
